package com.yiwei.zxp.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yiwei.zxp.Application;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.ComboBindCardBean;
import com.yiwei.zxp.api.bean.ComboCreditBean;
import com.yiwei.zxp.api.bean.ComboPayBean;
import com.yiwei.zxp.api.bean.UploadImgBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.ImageUtil;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.PreferenceUtils;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.UlineSurePayFinishDilaog;
import com.yiwei.zxp.view.V19FrameLayout;
import com.yiwei.zxp.view.uploadImage.UploadImgAdapter;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class UlinePayFinishActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.edit_account)
    EditText editAccount;
    @BindView(R.id.btn_clear)
    ImageView btnClear;
    @BindView(R.id.btn_reupload)
    TextView btnReupload;
    @BindView(R.id.img_uline)
    ImageView imgUline;
    @BindView(R.id.btn_uline_add)
    LinearLayout btnUlineAdd;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;

    private Unbinder unbiner;
    private UploadImgAdapter uploadImgAdapter;
    private String imgUploadUrl;
    private UlineSurePayFinishDilaog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uline_pay_finish);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("完成支付");
        txtRight.setText("客服");
        txtRight.setVisibility(View.VISIBLE);
        Util.setBankChange(editAccount);
        String order_number = getIntent().getStringExtra("order_number");
        boolean is_has_upload = getIntent().getBooleanExtra("is_has_upload", false);
        if (!TextUtils.isEmpty(order_number)) {

            dialog = new UlineSurePayFinishDilaog(this).setOnChooseListener(new UlineSurePayFinishDilaog.OnChooseListener() {
                @Override
                public void onSuccess(String account) {
                    getBindBank(order_number, account.replaceAll(" ", ""), imgUploadUrl);
                }
            });
            btnSubmit.setSelected(true);
        }
        if (is_has_upload) {
            getComboCredit(order_number);
        }
    }

    public void getComboCredit(String order_number) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        ComboCreditBean bean = new ComboCreditBean();
        bean.order_number = order_number;

        Api.api_service.getComboCredit(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    imgUploadUrl = result.datas.credit_img;
                    Glide.with(this).load(result.datas.credit_img).asBitmap().into(imgUline);

                    setData(result.datas.bankcard_no);
                    btnUlineAdd.setVisibility(View.GONE);
                    btnReupload.setVisibility(View.VISIBLE);
                });
    }

    public void setData(String account) {
        StringBuilder str = new StringBuilder(account.replace(" ", ""));

        int i = str.length() / 4;
        int j = str.length() % 4;

        for (int x = (j == 0 ? i - 1 : i); x > 0; x--) {
            str = str.insert(x * 4, " ");
        }

        editAccount.setText(str);
    }


    //10.4、绑定支付银行卡账号
    public void getBindBank(String order_num, String bank_num, String imgUploadUrl) {
        //    "全部", "待付款", "已付款"
        //状态（0：过期，1:有效，2：已使用)
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        ComboBindCardBean bean = new ComboBindCardBean();
        bean.bankcard_no = bank_num;
        bean.order_number = order_num;
        bean.credit_img = imgUploadUrl;
        Api.api_service.getComboBindCard(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    dialog.dismiss();
                    Dialog.showDefaultDialog(this, "", "待平台核对银行卡账号，\n请保持手机号码通畅！", "", "好", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            finish();
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                });
    }

    public void getUploadImg(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.getUploadImg(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "上传成功");
                    Glide.with(this).load(result.datas.url).asBitmap().into(imgUline);
                    imgUploadUrl = result.datas.url;
                    btnSubmit.setSelected(true);
                    btnUlineAdd.setVisibility(View.GONE);
                    btnReupload.setVisibility(View.VISIBLE);
                });
    }


    private void goToTakePhoto() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (uploadImgAdapter == null) {
                    initUploadImgAdapter();
                }
                uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImg(file);

                }
            }

            @Override
            public void callTake(File file, int mode) {

            }
        }, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.txt_right, R.id.btn_back, R.id.btn_clear, R.id.btn_reupload, R.id.btn_uline_add, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                Util.startActivity(this, WechatChatActivity.class);
                break;
            case R.id.btn_clear:
                editAccount.setText("");
                break;
            case R.id.btn_reupload:
                goToTakePhoto();
                break;
            case R.id.btn_uline_add:
                goToTakePhoto();
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editAccount))) {
                    ToastUtil.makeText(this, "银行卡号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(imgUploadUrl)) {
                    ToastUtil.makeText(this, "凭证不能为空");
                    return;
                }
                dialog.setData(UI.toString(editAccount));
                dialog.show();
                break;
        }
    }
}
